<?php
/**
 * Created by PhpStorm.
 * User: xf
 * Date: 2018/5/30
 * Time: 14:22
 */

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Utils\wx\SmallProgram;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

use App\Http\Utils\Time;

class LoginController extends Controller
{
    public function index(Request $request)
    {
        $dt = $request->all();
        $user_id = DB::table('user')
            ->where([
                ['openid', '=', $dt['openId']]
            ])->value('id');
        if (is_null($user_id)) {
            $user_id = DB::table('user')
                ->insertGetId([
                    'openId'      => $dt['openId'],
                    'nickName'    => $dt['nickName'],
                    'avatarUrl'   => $dt['avatarUrl'],
                    'gender'      => $dt['gender'],
                    'user_info'   => json_encode($dt),
                    'update_time' => Time::current(),
                    'create_time' => Time::current(),
                ]);
        }
        Cache::put('user', $user_id,3600);
        return $this->json(['user_id' => $user_id], 200, 'ok');
    }

    public function reLogin()
    {
        return $this->json('', 417, '请上传用户信息');
    }

    /**
     * 通过js_code 获取openId
     * @param $jsCode
     * @return mixed
     */
    public function getOpenId($jsCode)
    {
        $smallProgram = new SmallProgram($jsCode);
        return $smallProgram->getOpenIdByJsCode();
    }
}
